import { memo, useEffect } from "react"
import type { Station } from "../services"
import { modifyFeeInfo } from "../services"
import { Button, Col, Drawer, Form, Input, InputNumber, List, Modal, Row, Select, Space, TimePicker, message } from "antd"
import { MinusCircleOutlined, PlusCircleOutlined } from "@ant-design/icons"
import { Access, styled } from "@umijs/max"
import { useRequest } from "ahooks"
import dayjs from "dayjs"

const Footer = styled.div`
  width: 100%;
  height: 64px;
  flex-shrink: 0;
  box-shadow: 0px 0px 15px 0px rgba(0,0,0,0.05);
  bottom: 0;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
`
const TypeOptions = [
  {label: '尖时', value: 0},
  {label: '峰时', value: 1},
  {label: '平时', value: 2},
  {label: '谷时', value: 3},
  {label: '深谷时', value: 4},
]
const initValues = {
  jianElectricFee: 0.0001,
  jianServiceFee: 0.0001,
  fengElectricFee: 0.0001,
  fengServiceFee: 0.0001,
  pingElectricFee: 0.0001,
  pingServiceFee: 0.0001,
  guElectricFee: 0.0001,
  guServiceFee: 0.0001,
  shenGuElectricFee: 0.0001,
  shenGuServiceFee: 0.0001,
  feeList: [{
    type: 0,
    start: dayjs().hour(0).minute(0),
    end: dayjs().hour(23).minute(59),
    electricFee: 0.0001,
    serviceFee: 0.0001,
  }]
}
const Hours: number[] = new Array(24).fill(0).map((_,i) => i)
const Minutes: number[] = new Array(60).fill(0).map((_,i) => i)

export interface FeeModalProps {
  open?: boolean
  station?: Station.Entity
  editable?: boolean
  onCancel?: (refresh?: boolean) => void
}

const FeeModal: React.FC<FeeModalProps> = props => {
  const [feeForm] = Form.useForm()
  const modifyReq = useRequest(modifyFeeInfo, {manual: true})

  const onCancel = (refresh?: boolean) => {
    props.onCancel?.(refresh)
  }

  const onOk = () => {
    feeForm.validateFields().then((formValues: any) => {
      const {
        jianElectricFee, jianServiceFee, fengElectricFee, fengServiceFee,
        pingElectricFee, pingServiceFee, guElectricFee, guServiceFee, 
        shenGuElectricFee, shenGuServiceFee, feeList
      } = formValues
      const params = [
        [
          jianElectricFee, jianServiceFee, fengElectricFee, fengServiceFee,
          pingElectricFee, pingServiceFee, guElectricFee, guServiceFee,
          shenGuElectricFee, shenGuServiceFee, 0, 0, 0, 0, 0, 0,
        ]
      ]
      feeList.forEach((item: any) => {
        params.push([item.end.hour() * 100 + item.end.minute(), item.type])
      })
      if (params.at(-1)![0] !== 2359) {
        message.error({content: '尚有剩余时间未分配，请继续添加'})
      } else {
        modifyReq.runAsync({
          id: props.station!.id,
          feeInfo: JSON.stringify(params)
        }).then(() => {
          onCancel(true)
        })
      }
    })
  }

  const getDisabledTime = (index: number) => {
    const feeList = feeForm.getFieldValue('feeList')
    const before = feeList[index].start
    let after: any = undefined
    if (index < feeList.length - 1) {
      after = feeList[index + 1].end
    }
    let beforeHour = before.hour()
    if (before.minute() === 30 && beforeHour < 23) {
      beforeHour += 1
    }
    let afterHour = after?.hour() || 23
    if (after?.minute() === 0) {
      afterHour -= 1
    }
    return {
      disabledHours: () => Hours.filter(it => it < beforeHour || it > afterHour),
      disabledMinutes: (h: number) => {
        if (h === before.hour()) {
          if (h === 23) return Minutes.filter(it => it !== 59)
          return Minutes.filter(it => it !== 30)
        } else if (h === after?.hour()) {
          if (h === 23 && after?.minute() === 59)
            return Minutes.filter(it => ![0, 30].includes(it))
          return Minutes.filter(it => it !== 0)
        } else if (h > afterHour || h < beforeHour) {
          return Minutes
        } else if (h === 23) {
          return Minutes.filter(it => ![0, 30, 59].includes(it))
        }
        return Minutes.filter(it => ![0, 30].includes(it))
      }
    }
  }

  const addRow = (index: number, add: (values: any) => void) => {
    const feeList = feeForm.getFieldValue('feeList')
    const current = feeList[index]
    if (current.end.hour() === 23 && current.end.minute() === 59) {
      Modal.warn({
        title: '提醒',
        content: '已无可分配时间'
      })
      return
    }
    const jianElectricFee = feeForm.getFieldValue('jianElectricFee')
    const jianServiceFee = feeForm.getFieldValue('jianServiceFee')
    add({
      type: 0,
      start: current.end,
      end: dayjs().hour(23).minute(59),
      electricFee: jianElectricFee,
      serviceFee: jianServiceFee
    })
  }

  const onValuesChange = (changeValues: any, allValues: any) => {
    if (changeValues.hasOwnProperty('jianElectricFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 0) return item
        return {...item, electricFee: changeValues.jianElectricFee}
      }))
    } else if (changeValues.hasOwnProperty('jianServiceFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 0) return item
        return {...item, serviceFee: changeValues.jianServiceFee}
      }))
    } else if (changeValues.hasOwnProperty('fengElectricFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 1) return item
        return {...item, electricFee: changeValues.fengElectricFee}
      }))
    } else if (changeValues.hasOwnProperty('fengServiceFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 1) return item
        return {...item, serviceFee: changeValues.fengServiceFee}
      }))
    } else if (changeValues.hasOwnProperty('pingElectricFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 2) return item
        return {...item, electricFee: changeValues.pingElectricFee}
      }))
    } else if (changeValues.hasOwnProperty('pingServiceFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 2) return item
        return {...item, serviceFee: changeValues.pingServiceFee}
      }))
    } else if (changeValues.hasOwnProperty('guElectricFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 3) return item
        return {...item, electricFee: changeValues.guElectricFee}
      }))
    } else if (changeValues.hasOwnProperty('guServiceFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 3) return item
        return {...item, serviceFee: changeValues.guServiceFee}
      }))
    } else if (changeValues.hasOwnProperty('shenGuElectricFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 4) return item
        return {...item, electricFee: changeValues.shenGuElectricFee}
      }))
    } else if (changeValues.hasOwnProperty('shenGuServiceFee')) {
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any) => {
        if (item.type !== 4) return item
        return {...item, serviceFee: changeValues.shenGuServiceFee}
      }))
    } else if (changeValues.hasOwnProperty('feeList')) {
      const index = changeValues.feeList.findIndex((item: any) => !!item)
      feeForm.setFieldValue('feeList', allValues.feeList.map((item: any, idx: number) => {
        let electricFee = 0, serviceFee = 0
        switch (item.type) {
          case 0: electricFee = allValues.jianElectricFee; serviceFee = allValues.jianServiceFee; break
          case 1: electricFee = allValues.fengElectricFee; serviceFee = allValues.fengServiceFee; break
          case 2: electricFee = allValues.pingElectricFee; serviceFee = allValues.pingServiceFee; break
          case 3: electricFee = allValues.guElectricFee; serviceFee = allValues.guServiceFee; break
          case 4: electricFee = allValues.shenGuElectricFee; serviceFee = allValues.shenGuServiceFee; break
        }
        if (index + 1 === idx) {
          console.log(allValues.feeList[index])
          return {...item, electricFee, serviceFee, start: allValues.feeList[index].end}
        }
        return {...item, electricFee, serviceFee}
      }))
    }
  }

  useEffect(() => {
    if (props.station) {
      const _feeList = JSON.parse(props.station.feeInfo || '[]')
      const _prices = _feeList[0]
      if (_feeList.length && _prices.length >= 8) {
        const __feeList: any[] = []
        let previousEndTime = [0, 0]
        _feeList.forEach((item: any, index: number) => {
          if (index === 0) return
          const endHour = Math.floor(item[0] / 100)
          const endMinute = item[0] % 100
          __feeList.push({
            type: item[1],
            start: dayjs().hour(previousEndTime[0]).minute(previousEndTime[1]),
            end: dayjs().hour(endHour).minute(endMinute),
            electricFee: _prices[item[1] * 2],
            serviceFee: _prices[item[1] * 2 + 1]
          })
          previousEndTime = [endHour, endMinute]
        })
        feeForm.setFieldsValue({
          jianElectricFee: _prices[0],
          jianServiceFee: _prices[1],
          fengElectricFee: _prices[2],
          fengServiceFee: _prices[3],
          pingElectricFee: _prices[4],
          pingServiceFee: _prices[5],
          guElectricFee: _prices[6],
          guServiceFee: _prices[7],
          shenGuElectricFee: _prices[8],
          shenGuServiceFee: _prices[9],
          feeList: __feeList,
        })
      } else {
        feeForm.setFieldsValue(initValues)
      }
    }
  }, [props.station])

  return (
    <Drawer
      title='电价设置'
      width={1200}
      open={props.open}
      onClose={() => onCancel()}
      styles={{
        body: {
          padding: 0,
          display: 'flex',
          flexDirection: 'column',
        }
      }}
    >
      <div style={{flex: 1, overflowY: 'auto', padding: 24}}>
        <div style={{whiteSpace: 'pre-line'}}>
          {
            `说明：
              1、针对峰尖平谷深谷时间您可以自行调整，第一个结束时间调整后，第二个开始时间自动调整，依此类推，从上往下进行修改。
              2、默认四个峰尖谷平，您可以点击“添加计费区间”设置更加细致的计费时段。
            `
          }
        </div>
        <Form form={feeForm} style={{marginTop: 24}} onValuesChange={onValuesChange}>
          <List style={{border: '1px solid #eeeeee'}} header={<div style={{marginLeft: 16}}>电价策略</div>}>
            <List.Item style={{padding: '16px'}}>
              <Row style={{width: '100%'}} gutter={16}>
                <Col span={4} style={{display: 'flex', alignItems: 'center'}}>尖时</Col>
                <Col span={10}>
                  <Form.Item label='电费（元）' name='jianElectricFee' style={{margin: 0}} rules={[{required: true, message: '请输入尖时电费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
                <Col span={10}>
                  <Form.Item label='服务费（元）' name='jianServiceFee' style={{margin: 0}} rules={[{required: true, message: '请输入尖时服务费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
              </Row>
            </List.Item>
            <List.Item style={{padding: '16px'}}>
              <Row style={{width: '100%'}} gutter={16}>
                <Col span={4} style={{display: 'flex', alignItems: 'center'}}>峰时</Col>
                <Col span={10}>
                  <Form.Item label='电费（元）' name='fengElectricFee' style={{margin: 0}} rules={[{required: true, message: '请输峰尖时电费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
                <Col span={10}>
                  <Form.Item label='服务费（元）' name='fengServiceFee' style={{margin: 0}} rules={[{required: true, message: '请输峰尖时服务费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
              </Row>
            </List.Item>
            <List.Item style={{padding: '16px'}}>
              <Row style={{width: '100%'}} gutter={16}>
                <Col span={4} style={{display: 'flex', alignItems: 'center'}}>平时</Col>
                <Col span={10}>
                  <Form.Item label='电费（元）' name='pingElectricFee' style={{margin: 0}} rules={[{required: true, message: '请输平尖时电费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
                <Col span={10}>
                  <Form.Item label='服务费（元）' name='pingServiceFee' style={{margin: 0}} rules={[{required: true, message: '请输平尖时服务费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
              </Row>
            </List.Item>
            <List.Item style={{padding: '16px'}}>
              <Row style={{width: '100%'}} gutter={16}>
                <Col span={4} style={{display: 'flex', alignItems: 'center'}}>谷时</Col>
                <Col span={10}>
                  <Form.Item label='电费（元）' name='guElectricFee' style={{margin: 0}} rules={[{required: true, message: '请输入谷时电费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
                <Col span={10}>
                  <Form.Item label='服务费（元）' name='guServiceFee' style={{margin: 0}} rules={[{required: true, message: '请输入谷时服务费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
              </Row>
            </List.Item>
            <List.Item style={{padding: '16px'}}>
              <Row style={{width: '100%'}} gutter={16}>
                <Col span={4} style={{display: 'flex', alignItems: 'center'}}>深谷时</Col>
                <Col span={10}>
                  <Form.Item label='电费（元）' name='shenGuElectricFee' style={{margin: 0}} rules={[{required: true, message: '请输入深谷时电费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
                <Col span={10}>
                  <Form.Item label='服务费（元）' name='shenGuServiceFee' style={{margin: 0}} rules={[{required: true, message: '请输入深谷时服务费'}]}>
                    <InputNumber placeholder="请输入" style={{width: '100%'}} precision={4} min={0.0001} />
                  </Form.Item>
                </Col>
              </Row>
            </List.Item>
          </List>
          <List style={{border: '1px solid #eeeeee', marginTop: 24}} header={<Row style={{padding: '0 16px'}}>
            <Col span={4}>电价类型</Col>
            <Col span={10}>电价时段</Col>
            <Col span={5}>电费（元）</Col>
            <Col span={5}>服务费（元）</Col>
          </Row>}>
            <Form.List name='feeList'>
              {(fields, { add, remove }) => {
                return fields.map((field, index) => (
                  <Row key={field.key} style={{width: '100%', padding: 16}} gutter={16}>
                    <Col span={4}>
                      <Form.Item name={[field.name, 'type']} style={{margin: 0}}>
                        <Select options={TypeOptions} style={{width: '100%'}} allowClear={false} />
                      </Form.Item>
                    </Col>
                    <Col span={10}>
                      <Space>
                        <Form.Item name={[field.name, 'start']} style={{margin: 0}}>
                          <TimePicker format='HH:mm' disabled />
                        </Form.Item>
                        <Form.Item name={[field.name, 'end']} style={{margin: 0}}>
                          <TimePicker
                            format='HH:mm' allowClear={false} showNow={false}
                            disabledTime={() => getDisabledTime(index)}
                            hideDisabledOptions
                          />
                        </Form.Item>
                      </Space>
                    </Col>
                    <Col span={5}>
                      <Form.Item name={[field.name, 'electricFee']} style={{margin: 0}}>
                        <Input variant="borderless" readOnly style={{padding: 0}} />
                      </Form.Item>
                    </Col>
                    <Col span={5}>
                      <div style={{display: 'flex', justifyContent: 'space-between'}}>
                        <Form.Item name={[field.name, 'serviceFee']} style={{margin: 0}}>
                          <Input variant="borderless" readOnly style={{padding: 0}} />
                        </Form.Item>
                        <Space>
                          <Access accessible={index === fields.length - 1}>
                            <PlusCircleOutlined style={{color: 'green', cursor: 'pointer'}} onClick={() => addRow(index, add)} />
                          </Access>
                          <Access accessible={index === fields.length - 1 && index > 0}>
                            <MinusCircleOutlined style={{color: 'red', cursor: 'pointer'}} onClick={() => remove(index)} />
                          </Access>
                        </Space>
                      </div>
                    </Col>
                  </Row>
                ))
              }}
            </Form.List>
          </List>
        </Form>
      </div>
      <Footer>
        <Space>
          <Button type="primary" loading={modifyReq.loading} onClick={onOk}>保存</Button>
          <Button onClick={() => onCancel(false)}>取消</Button>
        </Space>
      </Footer>
    </Drawer>
  )
}

export default memo(FeeModal)